//
//  HomePageController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/20.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "HomePageController.h"
#import "HomePageCell.h"
#import "OrderDetailViewController.h"
#import "LoginViewController.h"
#import "HomePageModel.h"
#import "FinishedViewController.h"

@interface HomePageController ()<UITableViewDataSource,UITableViewDelegate,BMKMapViewDelegate,BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,CLLocationManagerDelegate,UITabBarDelegate,UITabBarControllerDelegate>
{
    BMKGeoCodeSearch* _geocodesearch;
    CLLocationCoordinate2D centerCoor;
    BOOL topLat;
}

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ViewwitdhLine;
@property (weak, nonatomic) IBOutlet UITableView *HomePageTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *HeightLine;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic,strong)NSMutableArray *requsetArray;
@property (nonatomic,assign)NSInteger page;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (nonatomic, weak) NSTimer *timer;
@property (strong, nonatomic) IBOutlet UIImageView *nothingImage;
@property (strong, nonatomic) IBOutlet UILabel *nothingLabel;

@end

@implementation HomePageController
- (CLLocationManager *) locationManager {
    if (_locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc]init];
    }
    return _locationManager;
}

- (NSMutableArray *)requsetArray
{
    if (!_requsetArray) {
        self.requsetArray = [NSMutableArray new];
    }
    return  _requsetArray;
}


- (void)viewDidLoad {
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.labelText = @"正在定位,请稍等...";
    [self.view addSubview:hud];
    [hud show:YES];
    self.tabBarController.delegate = self;
    topLat = NO;
//    [self addRightButtonWithImage:[UIImage imageNamed:@"刷新"]];
    self.hidesBottomBarWhenPushed = NO;
    [self.HomePageTableView registerNib:[UINib nibWithNibName:@"HomePageCell" bundle:nil] forCellReuseIdentifier:@"HomePageCellIdentifier"];
    self.HomePageTableView.showsVerticalScrollIndicator = NO;
    self.HeightLine.constant = 50*(ScreenWidth/375);
    self.page = 1;
    [self locationService];
    // 添加上拉刷新控件
    [self.HomePageTableView addFooterWithTarget:self action:@selector(loadMoreData)];
    // 添加下拉刷新控件
    [self.HomePageTableView addHeaderWithTarget:self action:@selector(loadOnePageData)];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(LoadTabeView:) name:@"LoadTableView" object:nil];
    [super viewDidLoad];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:30.0f
                                              target:self
                                            selector:@selector(timerFire)
                                            userInfo:nil
                                             repeats:YES];
    [_timer fire];
    
}

-(void)timerFire {
    [self loadOnePageData];
    NSLog(@"自动刷新订单");
}

- (void)addRightButtonWithImage:(UIImage *)image {
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setFrame:CGRectMake(0, 0, 20,20)];
    [rightButton setImageEdgeInsets:UIEdgeInsetsMake(0 , 0, 0, 0)];
    [rightButton setImage:image forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightBar_Touched:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
}

-(void)LoadTabeView:(NSNotification *)nit
{
    NSString *userid = [[NSUserDefaults standardUserDefaults]objectForKey:KUserDefaultsUserIdKey];
    self.page = 1;
    [self webRequest_orderList:userid AndBMKLocationService:centerCoor];
}

-(void)rightBar_Touched:(UIButton *)sender
{
    self.page = 1;
    [self locationService];
}

- (void)loadMoreData
{
    NSString *userid = [[NSUserDefaults standardUserDefaults]objectForKey:KUserDefaultsUserIdKey];
    self.page++;
    [self webRequest_orderList:userid AndBMKLocationService:centerCoor];
}

- (void)loadOnePageData
{
    self.page = 1;
    [self locationService];
}

-(void)webRequest_orderList:(NSString *)uid AndBMKLocationService:(CLLocationCoordinate2D)loc
{
    if (self.page == 1) {
        [self.requsetArray removeAllObjects];
    }
    NSString *lon =[NSString stringWithFormat:@"%f",loc.longitude];
    NSString *lat = [NSString stringWithFormat:@"%f",loc.latitude];
    NSDictionary *dict = [[NSDictionary alloc]init];
    dict = @{@"uid":uid,@"lon":lon,@"lat":lat,@"page":[NSString stringWithFormat:@"%ld",self.page]};
    topLat =YES;
    [HttpRequestManager getMethod:KemployeeOrderListInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([[response[@"status"] stringValue] isEqualToString:@"1"]) {
            NSMutableArray *array = response[@"orderlist"];
            for (int i = 0; i<array.count; i++) {
                HomePageModel *model = [HomePageModel modelToDictionary:array[i]];
                [self.requsetArray insertObject:model atIndex:0];
            }
            [self.HomePageTableView reloadData];
        }
        [self.HomePageTableView footerEndRefreshing];
        [self.HomePageTableView headerEndRefreshing];
    }];
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if(!topLat)    //"我的账号"
    {
        return NO;
    }else{
        return YES;
    }
}

-(void)viewWillDisappear:(BOOL)animated {
    _locService.delegate = nil;
    _geocodesearch.delegate = nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LoadTableView" object:nil];
}

//页面消失，进入后台不显示该页面，关闭定时器
-(void)viewDidDisappear:(BOOL)animated
{
    //关闭定时器
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.HomePageTableView reloadData];
    //开启定时器
    [self.timer setFireDate:[NSDate distantPast]];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"SelectWindowView" object:nil];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.071 green:0.075 blue:0.078 alpha:1.000]; //bar背景颜色
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont boldSystemFontOfSize:18]}; //标题颜色
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
}

-(void)locationService
{
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [_locService startUserLocationService];
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 反地理编码
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
        pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
            _locService.userLocation.location.coordinate.longitude};
        BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeocodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
        if(flag)
        {
            //NSLog(@"反地理编码检索发送成功");
        }
        else
        {
            NSLog(@"反地理编码检索发送失败");
        }
    });

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma UITableViewDataSource And UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.requsetArray.count > 0) {
        self.nothingImage.hidden = self.nothingLabel.hidden = YES;
    }else{
        self.nothingImage.hidden = self.nothingLabel.hidden = NO;
    }
    return self.requsetArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    HomePageCell *cell= [tableView dequeueReusableCellWithIdentifier:@"HomePageCellIdentifier"];
    HomePageModel *model = self.requsetArray[indexPath.section];
    [cell setHomepageModel:model];
    cell.ReturnStringBlock =^(NSString *oid,NSString *sn){
        [self webRequest_GrabOrderOid:oid SN:sn];
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
    HomePageModel *model = self.requsetArray[indexPath.section];
    OrderDetailViewController *orderVC = [[OrderDetailViewController alloc]init];
    NSString *lon =[NSString stringWithFormat:@"%f",centerCoor.longitude];
    NSString *lat = [NSString stringWithFormat:@"%f",centerCoor.latitude];
    orderVC.hidesBottomBarWhenPushed = YES;
    orderVC.snid = model.sn;
    orderVC.oid = model.oid;
    orderVC.lon = lon;
    orderVC.lat = lat;
    orderVC.is_grab = model.is_grab;
    [self.navigationController pushViewController:orderVC animated:YES];
}

#pragma mark - UITableViewDelegate
-(nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * sectionView = [[UIView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth, 12)];
    sectionView.backgroundColor = [UIColor clearColor];
    return sectionView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 12;
}

-(void)webRequest_GrabOrderOid:(NSString *)oid SN:(NSString *)sn
{
    NSString *lon =[NSString stringWithFormat:@"%f",centerCoor.longitude];
    NSString *lat = [NSString stringWithFormat:@"%f",centerCoor.latitude];
    NSString *userid = [[NSUserDefaults standardUserDefaults]objectForKey:KUserDefaultsUserIdKey];
    NSDictionary *dict = @{@"oid":oid,@"uid":userid,@"lon":lon,@"lat":lat};
    [HttpRequestManager postMethod:KemployeeOrderInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        if ([[response[@"status"] stringValue] isEqualToString:@"1"]) {
            FinishedViewController *finshVC = [[FinishedViewController alloc]init];
            finshVC.orderSN = sn;
            finshVC.finshedVCStr = @"抢单成功";
            finshVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:finshVC animated:YES];
        }else{
            [SVProgressHUD showErrorWithStatus:response[@"reason"]];
        }
    }];
}

#pragma mark ---定位delegate---
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == 0) {
        CLLocationCoordinate2D centerCoordinate = result.location;
        NSLog(@"*****%f %f*****",centerCoordinate.latitude, centerCoordinate.longitude);
        centerCoor = centerCoordinate;
        self.addressLabel.text = result.address;
        self.ViewwitdhLine.constant =result.address.length*16+35;
        NSString *userid = [[NSUserDefaults standardUserDefaults]objectForKey:KUserDefaultsUserIdKey];
        [self webRequest_orderList:userid AndBMKLocationService:centerCoordinate];
    }
}

/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
